/*
Copyright (c) 2008, Schley Andrew Kutz <sakutz@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.
    * Neither the name of l o s t c r e a t i o n s nor the names of its 
    contributors may be used to endorse or promote products derived from this 
    software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


package com.lostcreations.vitoolkitforjava.templateapplication;

import java.util.HashMap;
import com.vmware.vim25.*;
import org.apache.commons.cli.*;
import com.lostcreations.vitoolkitforjava.*;

public class Program
{
	private static class ProcessExit_Callback extends Thread
	{
		public void run()
		{
			try
			{
				if ( m_session.getIsConnected() ) m_session.disconnect();
			}
			catch ( Exception e )
			{
				System.out.println( "Error disconnecting: " + e.getMessage() );
			}
		}
	}
	
	/**
	 * The session object used to connect to the VI server.
	 */
	private static Session m_session;
	private static java.util.Properties m_props = new java.util.Properties();
	
	/**
	 * @param args
	 */
	public static void main( String[] args ) throws Exception
	{
		String cdir = new java.io.File( "." ).getCanonicalPath();
		String pfile = cdir + "/conf/unitTests.properties";
		java.io.FileInputStream fin = new java.io.FileInputStream( pfile );
		m_props.load( fin );
		fin.close();
		
		args = new String[] {
			"--server", m_props.getProperty( 
				"com.lostcreations.vitoolkitforjava.server" ),
			"--username", m_props.getProperty( 
			"com.lostcreations.vitoolkitforjava.username" ),
			"--password", m_props.getProperty( 
			"com.lostcreations.vitoolkitforjava.password" ),
			"--verbose", "--ignoresslerrors",
			"--vmname", m_props.getProperty( 
			"com.lostcreations.vitoolkitforjava.vm" )
		};
		
		// Create a new session.
		m_session = new Session( args );

		// Define the string that is prefixed to the auto-generated output
		// when the usage statement is printed.
		m_session.setHelpPrefix( "TemplateApplication" );

		// Cleanup when the process exists.
		java.lang.Runtime.getRuntime().addShutdownHook( 
			new ProcessExit_Callback() );

		// Add a custom option.
		m_session.addOptions( new Options().addOption(
			OptionBuilder
				.withLongOpt( "vmname" )
				.withDescription( "The name of the VM to find" )
				.isRequired()
				.create() ) );

		// Validate the options.
		try
		{
			m_session.validateOptions();
		}

		// If there is an error parsing the options print out the
		// generated usage statement with the given prefix, then
		// exit the application.
		catch ( ParseException e )
		{
			System.out.println( e.getMessage() );
			m_session.printUsage( "TemplateApplication" );
			return;
		}

		// Connect to the VI server.
		m_session.connect();

		// Create a filter to find the VM.
		HashMap<String, String> filters = 
			new HashMap<String, String>();
		filters.put( "config.name", 
			m_props.getProperty( 
				"com.lostcreations.vitoolkitforjava.vm" ) );

		// Find the VM that matches the given filter.
		ManagedObjectReference vm = m_session.findEntity(
			Session.EntityTypes.VirtualMachine,
			filters );

		// Make sure we found the VM
		if ( vm == null )
		{
			System.out.println( "Could not find the VM" );
			return;
		}

		// Get all of the VM's property values.
		HashMap<String, Object> values = m_session.getProperties( vm );

		// Make sure that values were returned
		if ( values.size() == 0 )
		{
			System.out.println( "Unable to retrieve property values" );
			return;
		}

		// Print out the VM's UUID
		System.out.println( "VM UUID: " +
			( ( VirtualMachineConfigInfo ) values.get( "config" ) ).getUuid() );
	}
}